package com.example.map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiBoundSearchOption;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final int GET_INFO = 1002;
    private MapView mMapView = null;
    /*private Button btnNormal;
    private Button btnsatellite;
    private Button btnTraffic;
    private Button btnLocation;*/
    private LocationClient mLocationClient;
    private LocationClientOption option;
    private UiSettings mUiSettings;
    private PoiSearch mPoiSearch;
    private Button btnCitySearch;
    private Button btnNearySearch;
    private Button btnAreaSearch;
    private LatLng mLatLng;
    private InfoWindow mInfoWindow;
    private Handler handler;
    private int GET_SCHOOL=1001;
    private Button btnBus;
    private Button btnCar;
    private RoutePlanSearch mSearch;
    private Button button;
    private AutoCompleteTextView tv_search;
    private List<String> resultList = new ArrayList<>();
    private OnGetPoiSearchResultListener poiSearchResultListener;
    private SuggestionSearch mSuggestionSearch;
    private TextWatcher textWatcher;
    private String key;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initfindViewById();


        resultList.add("广交");
        resultList.add("广交交通");
        resultList.add("广交交通集团");



        final ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_dropdown_item_1line, resultList);
        tv_search.setAdapter(adapter);

        mSuggestionSearch = SuggestionSearch.newInstance();
        OnGetSuggestionResultListener SuggestionResultlistener = new OnGetSuggestionResultListener() {
            @Override
            public void onGetSuggestionResult(SuggestionResult suggestionResult) {
                List<SuggestionResult.SuggestionInfo> suggestionInfos = suggestionResult.getAllSuggestions();
                resultList = new ArrayList<>();
                for (int i=1;i<suggestionInfos.size();i++){
                   Log.e(TAG,suggestionInfos.get(i).getKey());
                   resultList.add(suggestionInfos.get(i).getKey());
                }

                ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_dropdown_item_1line, resultList);
                tv_search.setAdapter(adapter);
                tv_search.removeTextChangedListener(textWatcher);
                tv_search.setText(key);
                tv_search.setSelection(key.length());
                tv_search.addTextChangedListener(textWatcher);



            }
        };
        mSuggestionSearch.setOnGetSuggestionResultListener(SuggestionResultlistener);



        textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                key = s.toString();
                if(key.length() == 0){
                    return;
                }

                mSuggestionSearch.requestSuggestion(new SuggestionSearchOption().city("广州").keyword(key));
            }
        };
        tv_search.addTextChangedListener(textWatcher);







        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what ==GET_SCHOOL){
                    String text = (String) msg.obj;
                    button.setText(text);
                    return true;

                }else if(msg.what ==GET_INFO){
                    String info = (String) msg.obj;
                    resultList.add(info);
                    Log.e(TAG,info);
                    return true;
                }
                return false;
            }
        });


        /*mSearch = RoutePlanSearch.newInstance();
        OnGetRoutePlanResultListener RoutePlanResultlistener = new OnGetRoutePlanResultListener() {

            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {
                //创建TransitRouteOverlay实例
                TransitRouteOverlay overlay = new TransitRouteOverlay(mMapView.getMap());
                //获取路径规划数据,(以返回的第一条数据为例)
                //为TransitRouteOverlay实例设置路径数据
                if (transitRouteResult.getRouteLines().size() > 0) {
                    overlay.setData(transitRouteResult.getRouteLines().get(0));
                    //在地图上绘制TransitRouteOverlay
                    overlay.addToMap();
                }
            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

            }

        };

        mSearch.setOnGetRoutePlanResultListener(RoutePlanResultlistener);
*/
        /**
         * 公交车导航
         */
        /*btnBus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlanNode stNode = PlanNode.withCityNameAndPlaceName("北京", "西二旗地铁站");
                PlanNode enNode = PlanNode.withCityNameAndPlaceName("北京", "百度科技园");

                mSearch.transitSearch((new TransitRoutePlanOption())
                        .from(stNode)
                        .to(enNode)
                        .city("北京"));
            }
        });

        *//**
         * 汽车导航
         *//*
        btnCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlanNode stNode = PlanNode.withCityNameAndPlaceName("北京", "西二旗地铁站");
                PlanNode enNode = PlanNode.withCityNameAndPlaceName("北京", "百度科技园");

                mSearch.drivingSearch((new DrivingRoutePlanOption())
                        .from(stNode)
                        .to(enNode));

            }
        });*/




        mMapView.getMap().setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                Log.e(TAG,"latLng:"+latLng.toString());
                mLatLng = latLng;
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });


        /**
         * setOnMarkerClickListener:点击marker显示内容
         */
        mMapView.getMap().setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                //用来构造InfoWindow的Button



                button.setBackgroundResource(R.drawable.border);

                mPoiSearch.searchNearby(new PoiNearbySearchOption()
                        .location(marker.getPosition())
                        .radius(1)
                        .keyword("学校"));



                //构造InfoWindow
                //point 描述的位置点
                //-100 InfoWindow相对于point在y轴的偏移量
                mInfoWindow = new InfoWindow(button, mLatLng, -100);

                //使InfoWindow生效
                mMapView.getMap().showInfoWindow(mInfoWindow);
                return true;
            }
        });





        /**
         * btnCitySearch：POi城市检索
         */
        btnCitySearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mPoiSearch.searchInCity(new PoiCitySearchOption().city("广州").keyword("高校").pageNum(10));
                mSuggestionSearch.requestSuggestion(new SuggestionSearchOption()
                        .city("广州")
                        .keyword("高校"));
            }
        });
        /**
         * btnNearySearch:POi按uid的周边检索
         */
        btnNearySearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mPoiSearch.searchPoiDetail(new PoiDetailSearchOption().poiUids("3c9a9e5b4b28ab522ee67b84"));

                mPoiSearch.searchNearby(new PoiNearbySearchOption()
                        .location(new LatLng(23.1881, 113.36024))
                        .radius(10000)
                        .keyword("学校"));

            }
        });
        /**
         * btnAreaSearch:区域检索
         */
        btnAreaSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                LatLng leftTop = new LatLng(mLatLng.latitude+0.05, mLatLng.longitude-0.05);
                LatLng rightBottom = new LatLng(mLatLng.latitude-0.05, mLatLng.longitude+0.05);
                LatLngBounds latLngBounds = new LatLngBounds.Builder().include(leftTop).include(rightBottom).build();
                mPoiSearch.searchInBound(new PoiBoundSearchOption().bound(latLngBounds).keyword("学校"));



            }
        });






       /* BaiduMap.OnMapClickListener listener = new BaiduMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {
                //使用BitmpDescriptor构造InfoWindow
                //用来构造InfoWindow的Button
                Button button = new Button(getApplicationContext());
                button.setBackgroundResource(R.drawable.border);
                button.setText("I LOVE CHINA");



                //构造InfoWindow
                //point 描述的位置点
                //-100 InfoWindow相对于point在y轴的偏移量
                InfoWindow mInfoWindow = new InfoWindow(button, point, -100);

                //使InfoWindow生效
                mMapView.getMap().showInfoWindow(mInfoWindow);
            }


            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        };
        //设置地图单击事件监听
        mMapView.getMap().setOnMapClickListener(listener);

*/



        /*//文字覆盖物
        //文字覆盖物位置坐标
        LatLng llText = new LatLng(39.86923, 116.397428);

        //构建TextOptions对象
        OverlayOptions mTextOptions = new TextOptions()
                .text("百度地图SDK") //文字内容
                .bgColor(0xAAFFFF00) //背景色
                .fontSize(24) //字号
                .fontColor(0xFFFF00FF) //文字颜色
                .rotate(-30) //旋转角度
                .position(llText);

        //在地图上显示文字覆盖物
        Overlay mText = mMapView.getMap().addOverlay(mTextOptions);*/

        /*//绘制圆
        //圆心位置
        LatLng center = new LatLng(39.90923, 116.447428);

        //构造CircleOptions对象
        CircleOptions mCircleOptions = new CircleOptions().center(center)
                .radius(1400)
                .fillColor(0xAA0000FF) //填充颜色
                .stroke(new Stroke(5, 0xAA00ff00)); //边框宽和边框颜色

        //在地图上显示圆
        Overlay mCircle = mMapView.getMap().addOverlay(mCircleOptions);

*/
        /*//构建折线点坐标
        LatLng p1 = new LatLng(39.920549, 116.39529);
        LatLng p2 = new LatLng(39.920549, 116.41340);
        LatLng p3 = new LatLng(39.907045, 116.41340);
        LatLng p4 = new LatLng(39.907045, 116.39529);
        List<LatLng> points = new ArrayList<LatLng>();
        points.add(p1);
        points.add(p2);
        points.add(p3);
        points.add(p4);

        //设置折线的属性
        OverlayOptions mOverlayOptions = new PolylineOptions()
                .width(1)
                .color(R.color.colorPrimary)
                .points(points);
        //在地图上绘制折线
        //mPloyline 折线对象
        Overlay mPolyline = mMapView.getMap().addOverlay(mOverlayOptions);*/

        /*mMapView.getMap().showMapPoi(false);

        BaiduMap.OnMapLongClickListener listener = new BaiduMap.OnMapLongClickListener() {

            @Override
            public void onMapLongClick(LatLng point) {


                //构建Marker图标
                BitmapDescriptor bitmap = BitmapDescriptorFactory
                        .fromResource(R.drawable.border);
                //构建MarkerOption，用于在地图上添加Marker
                OverlayOptions option1 = new MarkerOptions()
                        .position(point)
                        .icon(bitmap);
                //在地图上添加Marker，并显示
                mMapView.getMap().addOverlay(option1);
            }
        };
        //设置地图长按事件监听
        mMapView.getMap().setOnMapLongClickListener(listener);*/



        //点击事件
        /*BaiduMap.OnMapClickListener listener = new BaiduMap.OnMapClickListener() {
            *//**
             * 地图单击事件回调函数
             *
             * @param point 点击的地理坐标
             *//*
            @Override
            public void onMapClick(LatLng point) {
                Log.e(TAG,"OnMapClickListener   "+point);
            }

            *//**
             * 地图内 Poi 单击事件回调函数
             *
             * @param mapPoi 点击的 poi 信息
             *//*
            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        };
        //设置地图单击事件监听
        mMapView.getMap().setOnMapClickListener(listener);*/

        //双击事件
        /*BaiduMap.OnMapDoubleClickListener listener = new BaiduMap.OnMapDoubleClickListener() {
            *//**
             * 地图双击事件监听回调函数
             *
             * @param point 双击的地理坐标
             *//*
            @Override
            public void onMapDoubleClick(LatLng point) {
                Log.e(TAG,"OnMapClickListener   "+point);
            }
        };

        //设置地图双击事件监听
        mMapView.getMap().setOnMapDoubleClickListener(listener);*/

       /* //地图长按事件
        BaiduMap.OnMapLongClickListener listener = new BaiduMap.OnMapLongClickListener() {
            *//**
             * 地图长按事件监听回调函数
             *
             * @param point 长按的地理坐标
             *//*
            @Override
            public void onMapLongClick(LatLng point) {
                Log.e(TAG,"OnMapClickListener   "+point);
            }
        };
        //设置地图长按事件监听
        mMapView.getMap().setOnMapLongClickListener(listener);*/


        /*//改变地图缩放等级
        //直接缩放至缩放级别16
        mMapView.getMap().setMapStatus(MapStatusUpdateFactory.zoomTo(16));*/





        /*//改变Logo位置
        mMapView.setLogoPosition(LogoPosition.logoPostionleftTop);
        //显示隐藏指南针/比例尺/缩放按钮
        //实例化UiSettings类对象
        mUiSettings = mMapView.getMap().getUiSettings();
        //通过设置enable为true或false 选择是否显示指南针
        mUiSettings.setCompassEnabled(false);
        //比例尺
        mMapView.showScaleControl(false);
        //缩放按钮
        mMapView.showZoomControls(false);*/


        /*//地图手势
        //通过设置enable为true或false 选择是否启用地图平移
        mUiSettings.setScrollGesturesEnabled(true);
        //地图缩放
        mUiSettings.setZoomGesturesEnabled(true);
        //地图俯视（3D）
        mUiSettings.setOverlookingGesturesEnabled(false);
        //地图旋转
        mUiSettings.setRotateGesturesEnabled(false);
        //禁止一切手势
        mUiSettings.setAllGesturesEnabled(false);*/

/*
        btnNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //普通地图 ,mBaiduMap是地图控制器对象
                mMapView.getMap().setMapType(BaiduMap.MAP_TYPE_NORMAL);
            }
        });


        btnTraffic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //开启交通图
                mMapView.getMap().setTrafficEnabled(true);

            }
        });


        btnsatellite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //卫星地图
                mMapView.getMap().setMapType(BaiduMap.MAP_TYPE_SATELLITE);
            }
        });*/

        /*btnLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //定位初始化
                mLocationClient = new LocationClient(MainActivity.this);

                //通过LocationClientOption设置LocationClient相关参数
                option = new LocationClientOption();
                option.setOpenGps(true); // 打开gps
                option.setCoorType("bd09ll"); // 设置坐标类型
                option.setScanSpan(1000);

                //设置locationClientOption
                mLocationClient.setLocOption(option);

                //注册LocationListener监听器
                MyLocationListener myLocationListener = new MyLocationListener();
                mLocationClient.registerLocationListener(myLocationListener);
                //开启地图定位图层
                mLocationClient.start();
                mMapView.getMap().setMyLocationEnabled(true);


            }
        });*/
    }

    private void initfindViewById() {
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        /*btnNormal = findViewById(R.id.btn_mapnormal);
        btnsatellite = findViewById(R.id.btn_mapsatellite);
        btnTraffic = findViewById(R.id.btn_mapTraffic);
        btnLocation = findViewById(R.id.btn_mapLocation);*/
        mUiSettings = mMapView.getMap().getUiSettings();
        mPoiSearch  = PoiSearch.newInstance();
        btnCitySearch = findViewById(R.id.btn_poicitysearch);
        btnNearySearch = findViewById(R.id.btn_poinearysearch);
        btnAreaSearch = findViewById(R.id.btn_poiareasearch);
        btnBus = findViewById(R.id.btn_bus);
        btnCar = findViewById(R.id.btn_car);
        button = new Button(getApplicationContext());
        tv_search = findViewById(R.id.tv_search);




        poiSearchResultListener = new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                for (int i=0;i<poiResult.getAllPoi().size();i++){
                    PoiInfo poiInfo = poiResult.getAllPoi().get(i);
                    Log.e(TAG,poiInfo.name+"   "+poiInfo.address+"   "+poiInfo.uid);
                    String school = poiInfo.name+"    "+poiInfo.address;
                    Message msg = Message.obtain();
                    msg.what = GET_SCHOOL;
                    msg.obj  = school;
                    handler.sendMessage(msg);
                }

                //创建PoiOverlay对象
                PoiOverlay poiOverlay = new PoiOverlay(mMapView.getMap());
                //设置Poi检索数据
                poiOverlay.setData(poiResult);

                //将poiOverlay添加至地图兵缩放至合适级别
                poiOverlay.addToMap();
                poiOverlay.zoomToSpan();






            }

            @Override
            public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

            }

            @Override
            public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {
                /*Log.e(TAG, poiDetailSearchResult.getPoiDetailInfoList().get(0).getDetailUrl());*/
            }

            @Override
            public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

            }
        };

        mPoiSearch.setOnGetPoiSearchResultListener(poiSearchResultListener);

        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
        iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK);
        SDKReceiver mReceiver = new SDKReceiver();
        registerReceiver(mReceiver, iFilter);



    }

    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mLocationClient.stop();
        mMapView.getMap().setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        mPoiSearch.destroy();
        mSearch.destroy();

        super.onDestroy();
    }


    class MyLocationListener extends BDAbstractLocationListener {

        @Override

        public void onReceiveLocation(BDLocation bdLocation) {
            //mapView 销毁后不在处理新接收的位置
            if (bdLocation == null || mMapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder().accuracy(bdLocation.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(bdLocation.getDirection()).latitude(bdLocation.getLatitude()).longitude(bdLocation.getLongitude()).build();
            mMapView.getMap().setMyLocationData(locData);


        }


    }

    class SDKReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
                //key验证失败，做相应处理
            } else if (action.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK)) {
                //key验证成功，做相应处理
            }

        }
    }
}
